package com.kaishengit.dao;

import java.util.Iterator;
import java.util.List;

import com.kaishengit.dao.core.BaseDao;
import com.kaishengit.dao.core.Where;
import com.kaishengit.pojo.Contacts;
import com.kaishengit.pojo.User;
import com.kaishengit.pojo.UserGroup;

public class ContactsDao extends BaseDao<Contacts, String> {
    public List<Contacts> searchICanSee(List<Where> whereList, User user, UserGroup group) {
        List<Contacts> contactsList = find(whereList);
        String userView = "u:" + user.getId();
        String groupView = "";
        if (group != null) {
            groupView = "g:" + group.getId();
        }
        
        Iterator<Contacts> iterator = contactsList.iterator();
        while (iterator.hasNext()) {
            Contacts contacts = iterator.next();
            if (contacts.getView() != null) {
                if (!(contacts.getView().contains(userView) || contacts.getView().contains(groupView) || "all".equals(contacts.getView()))) {
                    iterator.remove();
                }
            } else {
                iterator.remove();
            }
        }
        return contactsList;
    }
    
    public List<Contacts> findICanSee(User user, UserGroup group) {
        String hql = "from Contacts where view is not null and (user = ? or view = 'all' or view like ? or view like ?) order by createTime desc";
        String first = "%u:" + user.getId() + "%";
        String second = "";
        if (group != null) {
            second = "%g:" + group.getId() + "%";
        }
        List<Contacts> contactsList = find(hql, user, first, second);
        return contactsList;
    }
    
    public List<Contacts> findAllContacts(User user, UserGroup group) {
        List<Contacts> contactsList = findICanSee(user, group);
        
        Iterator<Contacts> iterator = contactsList.iterator();
        while (iterator.hasNext()) {
            Contacts contacts = iterator.next();
            if (contacts.getName() == null) {
                    iterator.remove();
            } 
        }
        
        return contactsList;
    }
}
